// 登录与注册模块
import {reqGetCode, reqUserRegister,reqUserLogin, reqUserInfo,reqLogout} from '@/api/index'
import { setToken, getToken, removeToken } from '@/utils/token'

const state = {
  code: '',
  token: getToken(),
  userInfo: {}
}
const mutations = {
  GETCODE(state,code) {
    state.code = code
  },
  USERLOGIN(state,token) {
    state.token = token
  },
  GETUSERINFO(state,userInfo) {
    state.userInfo = userInfo
  },
  CLEAR(state) {
    // 把仓库当中的相关用户信息清空
    state.code = ''
    state.userInfo = {}
    // 把本地存储token数据清空
    state.token = removeToken()
  }
}
const actions = {
  // 获取验证码
  async getCode({commit}, phone) {
    // 获取验证码的接口：把验证码返回了，应该是发送到用户手机上，【要钱】，不干
    let result = await reqGetCode(phone)
    if(result.code == 200) {
      commit('GETCODE', result.data)
      return 'ok'
    } else {
      return Promise.reject(new Error('faile'))
    }
  },
  // 用户注册
  async userRegister({commit}, user) {
    let result = await reqUserRegister(user)
    if(result.code == 200) {
      return 'ok'
    } else {
      return Promise.reject(new Error('faile'))
    }
  },
  // 登录业务
  async userLogin({commit}, data) {
    let result = await reqUserLogin(data)
    if(result.code == 200) {
      // 服务器下发的token，是用户的唯一身份标识符
      commit('USERLOGIN', result.data.token)
      // 持久化存储token
      setToken(result.data.token)
      return 'ok'
    } else {
      return Promise.reject(new Error('faile'))
    }
  },
  // 获取用户信息
  async getUserInfo({commit}) {
    let result = await reqUserInfo()
    if(result.code == 200) {
      commit('GETUSERINFO', result.data)
      return 'ok'
    } else {
      return Promise.reject(new Error('faile'))
    }
  },
  // 退出登录
  async userLogout({commit}) {
    let result = await reqLogout()
    if(result.code == 200) {
      commit('CLEAR')
      return 'ok'
    } else {
      return Promise.reject(new Error('faile'))
    }

  }
}
const getters = {}

export default {
  state,
  mutations,
  actions,
  getters
}